<?php
namespace app\index\model;
use think\Db;
/**
 * Created by Submint Text.
 * User: hetaoren<452649510@qq.com>
 * Date: 2017/03/10
 * Explain: 积分日志类
 */
class IntegralLog extends Base{
     /**
      *  库存列表
      */
	public function pageQuery(){     
        $where = [];
        $user_id = session('user_id');
        if($user_id != '')$where['s.user_id'] = $user_id;
        $createTime = input('createTime');
        if($createTime!='')$where['s.createTime'] = ['like',"%$createTime%"];
        $user_name = input('user_name');
        if($user_name != '')$where['u.user_name'] = ['like',"%$user_name%"];
        $month = input('month');
        if($month != '')$where['s.createTime'] = ['like',"%$month%"]; 
		$page = Db::name('integralLog')->alias('s')->join('__USERS__ u','u.user_id=s.user_id','left')
		        ->where($where)->field('u.user_name,s.*')
		        ->order('logId desc')->paginate(input('pagesize/d'))->toArray();
		if(count($page['Rows'])>0){
			foreach ($page['Rows'] as $key => $v){
  				$page['Rows'][$key]['type'] = $v['type'] ? '增加' : '减少';
			}
		}
        $page['SumIntegral'] = Db::name('integralLog')->alias('s')->join('__USERS__ u','u.user_id=s.user_id','left')->where($where)->where('s.type',1)->sum('num')-Db::name('integralLog')->alias('s')->join('__USERS__ u','u.user_id=s.user_id','left')->where($where)->where('s.type',0)->sum('num');
		return $page;
	}

	/**
	 * 新增
	 */
	public function add($user_id,$type=0,$num=1,$desc=''){
		$data = [];
		$data["user_id"] = $user_id;
		$data["type"] = $type;
		$data["num"] = $num;
		$data["desc"] = $desc;
		$data["createTime"] = date('Y-m-d H:i:s');
		if($type == 0){				
	        $integral = model('users')->where(['user_id'=>$user_id,'dataFlag'=>1])->value('integral');
	        if($integral < $num)return HTRReturn('积分不足');
		}
		Db::startTrans();
		try{
			$result = $this->allowField(true)->save($data);
			if(false === $result)throw \Exception('日志生成失败');
			if($type){		
		    	$result = model('users')->where(['user_id'=>$user_id,'dataFlag'=>1])->setInc('integral',$num);
		    	if(false === $result)throw \Exception('积分修改失败');
			}else{
		    	$result = model('users')->where(['user_id'=>$user_id,'dataFlag'=>1])->setDec('integral',$num);	
		    	if(false === $result)throw \Exception('积分修改失败');
			}
        	Db::commit();
        	return HTRReturn("操作成功", 1);
		}catch (\Exception $e) {
            Db::rollback();
            return HTRReturn('操作失败');
        }
	}
}
